package com.anrongtec.zcpt.manager;

import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.base.BaseActivity;
import com.anrongtec.zcpt.manager.AppStateManager.AppStateListener;
import com.anrongtec.zcpt.module.AppModel;
import com.anrongtec.zcpt.util.Util;
import com.ansec.mdm.IPackageService;
import com.art.base.util.ApkUtils;
import com.art.base.util.DialogUtil;
import com.art.base.util.FileUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import java.util.ArrayList;
import java.util.List;

import static com.art.base.db.LiteOrmDBUtil.mContext;

/**
 * 应用卸载
 * 
 * @author dongtianhao
 *
 */
public class AppUninstallActivity extends BaseActivity {
	private final static int STATUS_DATA_UPDATE = 1;
	private final static int STATUS_DATA_EMPTY = 2;
	private final static int STATUS_DATA_SEARCH = 3;
	private static final long DELAYED_TIME = 500;
	private EditText et_app_uninstall_search;
	private RecyclerView rv_app_uninstall_manager;
	private EmptyWrapper empty;
	private List<AppModel> apps, appClone;
	private CommonAdapter<AppModel> adapter;
	private String hint;
	private List<AppModel> subData;
	private int currentPosition = -1;// 当前卸载APP的position 为了更新UI使用
	private AppStateManager mAppStateManager;
	private IPackageService mPackageService;//卸载器


	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case STATUS_DATA_UPDATE:
				empty.notifyDataSetChanged();
				// 更新edittext
				break;
			case STATUS_DATA_EMPTY:
				empty.setEmptyView(R.layout.empty_view);
				rv_app_uninstall_manager.setAdapter(empty);
				break;
			case STATUS_DATA_SEARCH:
				if (apps.size() == 0) {
					empty.setEmptyView(R.layout.empty_view);
					rv_app_uninstall_manager.setAdapter(empty);
				}
				empty.notifyDataSetChanged();
				break;
			}
			hint = getString(R.string.search_uninstall, apps.size());
			et_app_uninstall_search.setHint(hint);
		}
	};
	private ProgressDialog mLoadingDialog;
	// private APPReceiver receiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_app_uninstall);
		initViews();
		initEvents();
		initIntent();
		// registReceiver();
		initData();
		registAppStatus();
	}

	private void initIntent() {
		Intent intent = new Intent("com.ansec.mdm.action.PackageManager");
		intent.setPackage("com.ansec.mdm");
		mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE);
	}

	private ServiceConnection conn = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mPackageService = IPackageService.Stub.asInterface(service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mPackageService = null;
		}
	};

	private void registAppStatus() {
		mAppStateManager = new AppStateManager(this);
		mAppStateManager.begin(new AppStateListener() {

			@Override
			public void onAppUninstalled(String pkgName) {
				for (AppModel app : appClone) {
					if (app.getAppPackName().equals(pkgName)) {
						appClone.remove(app);
						break;
					}
				}
				apps.clear();
				apps.addAll(appClone);
				if (apps.isEmpty()) {
					handler.sendEmptyMessageDelayed(STATUS_DATA_EMPTY, DELAYED_TIME);
				} else {
					handler.sendEmptyMessageDelayed(STATUS_DATA_UPDATE, DELAYED_TIME);
				}

			}

			@Override
			public void onAppRelpaced(String pkgName) {

			}

			@Override
			public void onAppInstalled(String pkgName) {

			}
		}, true);
	}

	/**
	 * 注册广播接收器
	 */
	// private void registReceiver() {
	// IntentFilter filter = new IntentFilter();
	// filter.addAction(Intent.ACTION_PACKAGE_ADDED);
	// filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
	// filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
	// filter.addDataScheme("package");
	// receiver = new APPReceiver() {
	// @Override
	// public void receive(Context context, Intent intent, String packageName) {
	// for (int i = 0; i < appClone.size(); i++) {
	// if (appClone.get(i).getAppPackName().equals(packageName)) {
	// appClone.remove(i);
	// break;
	// }
	// }
	// Util.post(searchThread);
	// }
	// };
	// registerReceiver(receiver, filter);
	// }

	@Override
	protected void onDestroy() {
		mAppStateManager.unregisterListener();
		super.onDestroy();
	}

	@Override
	protected void initViews() {
		et_app_uninstall_search = (EditText) findViewById(R.id.et_app_uninstall_search);
		rv_app_uninstall_manager = (RecyclerView) findViewById(R.id.rv_app_uninstall_manager);

		initRecyclerView();
	}


	/**
	 * 初始化recyclerView
	 */
	private void initRecyclerView() {
		rv_app_uninstall_manager.setLayoutManager(new LinearLayoutManager(this));
		// 设置Item增加、移除动画
		rv_app_uninstall_manager.setItemAnimator(new DefaultItemAnimator());
		apps = new ArrayList<>();
		adapter = new CommonAdapter<AppModel>(this, R.layout.item_app, apps) {

			@Override
			protected void convert(ViewHolder holder, final AppModel info, final int position) {
				holder.setImageDrawable(R.id.iv_item_app_icon, info.getLocalIcon());
				holder.setText(R.id.tv_item_app_name, info.getAppName());
				holder.setStar(R.id.ratingbar_item_app_score, info.getScore() == 0 ? 3.5f : info.getScore());
				holder.setText(R.id.tv_item_app_version_name, info.getLocalVersionName());
				holder.setText(R.id.tv_item_app_total_size,
						FileUtils.formatFileSize(getApplicationContext(), info.getSize()));
				holder.setText(R.id.btn_item_app_install, "卸载");
				holder.setOnClickListener(R.id.btn_item_app_install, new OnClickListener() {

					@Override
					public void onClick(View v) {
						mLoadingDialog = DialogUtil.createLoadingDialog(AppUninstallActivity.this, "正在卸载...");
						ApkUtils.uninstall(AppUninstallActivity.this,info.getAppPackName());
						mLoadingDialog.dismiss();
						//广西的卸载
						/*try {
							mPackageService.uninstallPackage(info.getAppPackName(), new IResultListener.Stub() {
								@Override
								public void onResult(String result) throws RemoteException {
									mLoadingDialog.dismiss();
									if (!result.contains("200")) {
										ToastShow.shortMessage(AppUninstallActivity.this, "此应用无法卸载");
									}
								}
							});
						} catch (RemoteException e) {
                            mLoadingDialog.dismiss();
							e.printStackTrace();
						}*/
//						ApkUtils.uninstallSilent(AppUninstallActivity.this, info.getAppPackName());
						currentPosition = position;
					}
				});
			}

		};
		empty = new EmptyWrapper(adapter);
		empty.setEmptyView(R.layout.loading_view);

		rv_app_uninstall_manager.setAdapter(empty);
	}

	/***
	 * 初始化数据(已经安装的应用)
	 */
	@Override
	protected void initData() {

		Util.post(new Runnable() {
			@Override
			public void run() {
				apps.clear();
//				apps = DDApp.getInstance().getAppModels();
//				if(apps==null){
//					apps.addAll(Util.getAppsFromMaket(AppUninstallActivity.this));
//				}
				apps.addAll(Util.getAppsFromMaket(AppUninstallActivity.this));
				appClone = new ArrayList<>();
				for (AppModel app : apps) {
					appClone.add(app);
				}
				if (apps.isEmpty()) {
					handler.sendEmptyMessageDelayed(STATUS_DATA_EMPTY, DELAYED_TIME);
				} else {
					handler.sendEmptyMessageDelayed(STATUS_DATA_UPDATE, DELAYED_TIME);
				}
			}
		});
	}

	@Override
	protected void initEvents() {

		et_app_uninstall_search.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.length() == 0) {
					apps.clear();
					apps.addAll(appClone);
					empty.notifyDataSetChanged();
				} else {
					Util.post(searchThread);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
	}

	/**
	 * 搜索异步任务
	 */
	private Runnable searchThread = new Runnable() {
		@Override
		public void run() {
			String data = et_app_uninstall_search.getText().toString();
			getDataSub(appClone, data);
			apps.clear();
			apps.addAll(subData);
			handler.sendEmptyMessage(STATUS_DATA_SEARCH);
		}
	};

	/**
	 * 搜索list里是否含有相应的APP对象
	 * 
	 * @param data
	 * @param key
	 */
	private List<AppModel> getDataSub(List<AppModel> data, String key) {
		if (subData == null) {
			subData = new ArrayList<AppModel>();
		} else {
			subData.clear();
		}
		int length = data.size();
		for (int i = 0; i < length; ++i) {
			if (data.get(i).getAppName().contains(key)) {
				subData.add(data.get(i));
			}
		}
		return subData;
	}

	@Override
	protected void onCreateCustomToolBar(Toolbar toolbar) {
		toolbar.setTitle(getString(R.string.title_activity_app_uninstall));
		super.onCreateCustomToolBar(toolbar);
	}

}
